package com.zq.mycloud.gateway.config;

import com.zq.mycloud.gateway.util.IpUtil;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import reactor.core.publisher.Mono;

import java.util.Objects;


/**
 * @author ：zhang qiang
 * @package :com.zq.mycloud.gateway.config
 * @date ：Created in 2020/11/23 上午10:11
 * @description：默认按照ip限流，可在配置文件中自定义配置规则
 * @modified By：
 * @version: $
 */
@Configuration
public class GeneralConfig {

    /**
     * 默认按照Ip限流
     *
     * @return
     */
    @Primary
    @Bean
    public KeyResolver ipKeyResolver() {
        return exchange -> Mono.just(
                IpUtil.getIP(exchange.getRequest().getHeaders(), exchange.getRequest().getRemoteAddress())
        );
    }


    /**
     * 按照Path限流
     *
     * @return
     */
    @Bean
    public KeyResolver pathKeyResolver() {
        return exchange -> Mono.just(
                exchange.getRequest()
                        .getPath()
                        .value()
        );
    }


    /**
     * 按照指定header限流
     *
     * @return
     */
    @Bean
    public KeyResolver headerKeyResolver() {
        return exchange -> Mono.just(
                Objects.requireNonNull(exchange.getRequest()
                        .getHeaders().getFirst("userId"))
        );
    }
}